package com.lagou.login.interceptor;

import com.lagou.login.entiy.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description
 * @Author ch'ien
 * @Date 2021/4/26 15:17
 **/
public class RequestInterceptor implements HandlerInterceptor {

    /**
     * 之前执行（进入Handler处理之前）
     * 可以进行权限验证
     * @param request
     * @param response
     * @param handler
     * @return  true放行，false中止程序
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户登陆信息
        User user = (User) request.getSession().getAttribute("user");
        //判断用户是否有权限进入商家管理后台系统
        if(user != null && user.getId() > 0){
            //如果验证通过，则返回true，放行请求，即用户接下来的操作可以正常执行
            return true;
        }
        //如果不满足登陆验证，则跳转到登陆页面

        response.sendRedirect("/error.html?name="+ request.getLocalPort());
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
